package cn.com.openportal.ffw.common.utils;

import cn.com.openportal.ffw.common.exception.RRException;
import cn.com.openportal.ffw.modules.sys.entity.SysDeptEntity;
import cn.com.openportal.ffw.modules.sys.entity.SysUserEntity;
import cn.com.openportal.ffw.modules.sys.service.SysDeptService;
import cn.com.openportal.ffw.modules.sys.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author LeeSon QQ & WX:25901875
 * @version V1.0
 * @Package cn.com.openportal.ffw.common.utils
 * @create 2020-01-18 23:33
 * @Copyright © 2019 LeeSon QQ & WX:25901875
 */
@Component
public class BaseEntitySetValueUtils {
    private static Logger logger = LoggerFactory.getLogger(BaseEntitySetValueUtils.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;

    private static final String getDeptId = "getDeptId";
    private static final String getCreateUserId = "getCreateUserId";
    private static final String setDeptName = "setDeptName";
    private static final String setCreateUserName = "setCreateUserName";

    private Long getValue(Object obj, String methodName) throws Exception {
        Class<?> clazz = obj.getClass();
        Method method = clazz.getMethod(methodName);
        Long id = (Long) method.invoke(obj);
        return id;
    }

    private void setValue(Object obj, String methodName, String value) throws Exception {
        Class<?> clazz = obj.getClass();
        Method method = clazz.getMethod(methodName, String.class);
        method.invoke(obj, value);
    }

    public List BaseEntitySetValue(List list) {
        try {
            for (int i = 0; i < list.size(); i++) {
                Object e = list.get(i);
                if (null != getValue(e, getDeptId) && 0L != getValue(e, getDeptId)) {
                    SysDeptEntity sysDeptEntity = sysDeptService.getById(getValue(e, getDeptId));
                    if (null != sysDeptEntity) {
                        setValue(e, setDeptName, sysDeptEntity.getName());
                    }
                } else {
                    setValue(e, setDeptName, "NULL");
                }

                if (null != getValue(e, getCreateUserId) && 0L != getValue(e, getCreateUserId)) {
                    SysUserEntity sysUserEntity = sysUserService.getById(getValue(e, getCreateUserId));
                    if (null != sysUserEntity) {
                        setValue(e, setCreateUserName, sysUserEntity.getUsername());
                    }
                } else {
                    setValue(e, setCreateUserName, "NULL");
                }
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RRException("发生错误");
        }
    }
}
